//
//  MyPOSInactiveVC.m
//  NewPro
//
//  Created by 何荧红 on 2019/3/23.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "MyPOSInactiveVC.h"
#import "MyPOSlnactiveDirVC.h"
#import "POSListCell.h"
#import "PostlistModel.h"
#import "IQKeyboardManager.h"
#import "OrderCenterList.h"
#import "POSStore.h"

@interface MyPOSInactiveVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, assign) NSInteger VCType;

@property (nonatomic, strong) ViewHeader *secView;
@property (nonatomic, strong) ViewFoot *foot;
@property (nonatomic, strong) PushView *pushView;
@property (nonatomic, strong) PushView *success;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *ChooseButton;
@property (nonatomic, strong) UIButton *numberback;
@property (nonatomic, assign) BOOL isZ;
@property (nonatomic, assign) BOOL isPiliang;
@property (nonatomic, assign) NSInteger Fristindex;
@property (nonatomic, assign) NSInteger Secondindex;
@property (nonatomic, assign) BOOL isTimesort;
@property (nonatomic, copy) NSString *timesort;
@property (nonatomic, assign) BOOL isMonetsort;
@property (nonatomic, copy) NSString *moneysort;
@property (nonatomic, assign) NSInteger minPosFlow;
@property (nonatomic, assign) NSInteger Page;
@property (nonatomic, assign) NSInteger MaxPage;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *mutArr;

@end

@implementation MyPOSInactiveVC

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    return _dataArr;
}
- (NSMutableArray *)mutArr{
    if (!_mutArr) {
        _mutArr = [[NSMutableArray alloc]init];
    }
    return _mutArr;
}
- (void)setIsZ:(BOOL)isZ{
    _isZ = isZ;
    if (_isZ) {
        [self.ChooseButton setImage:[UIImage imageNamed:@"直接划拨"] forState:UIControlStateNormal];
    }else{
        [self.ChooseButton setImage:[UIImage imageNamed:@"划拨选择定向"] forState:UIControlStateNormal];
    }
}
- (PushView *)pushView{
    if (!_pushView) {
        _pushView = [[PushView alloc]initWithChooseAlert];
    }
    return _pushView;
}
- (void)setIsTimesort:(BOOL)isTimesort{
    _isTimesort = isTimesort;
    self.moneysort = @"";
    self.timesort = @"expire_start_time";
}
- (void)setIsMonetsort:(BOOL)isMonetsort{
    _isMonetsort = isMonetsort;
    self.timesort = @"";
    self.moneysort = @"back_amount";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCSS];
    [self getPOSlist];
}
- (void)initCSS{
    self.VCType = 0;
    self.timesort = @"";
    self.moneysort = @"";
    self.Page = 1;
    self.MaxPage = 1;
    WS(weakself);
    self.view.backgroundColor = [UIColor colorWithHexString:@"F4F4F4"];
    self.secView = [[ViewHeader alloc]initWithPostListHeader];
    [self.secView CleanPostlistSecView:self.VCType];
    [self.view addSubview:_secView];
    [self.secView setPiliangBlock:^(BOOL isP) {
        weakself.isPiliang = isP;
    }];
    //暂时注释
//    [self.secView setTimesortBlock:^(BOOL isT) {
//        weakself.isTimesort = isT;
//        if (weakself.dataArr.count > 0) {
//            [weakself.dataArr removeAllObjects];
//        }
//        weakself.Page = 1;
//        [weakself getPOSlist];
//    }];
    [self.secView setMoneysortBlock:^(BOOL isM) {
        weakself.isMonetsort = isM;
        if (weakself.dataArr.count > 0) {
            [weakself.dataArr removeAllObjects];
        }
        weakself.Page = 1;
        [weakself getPOSlist];
    }];
    self.foot = [[ViewFoot alloc]initWithBusinessChoose];
    self.foot.MyPOSListType = self.VCType;
    self.foot.numberfield.delegate = self;
    [self.foot setMoneytosureBlock:^{
        [weakself tofriendView];
    }];
    [self.foot setEditBlock:^{
        if (weakself.numberback.hidden) {
            weakself.numberback.hidden = NO;
        }
    }];
    [self.view addSubview:self.foot];
    self.ChooseButton = [[UIButton alloc]init];
    [self.ChooseButton addTarget:self action:@selector(ChooseTypeClik) forControlEvents:UIControlEventTouchUpInside];
    [self.ChooseButton setImage:[UIImage imageNamed:@"直接划拨"] forState:UIControlStateNormal];
    [self.view addSubview:self.ChooseButton];
    [self.ChooseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.foot.mas_top);
        make.width.mas_equalTo(140);
        make.height.mas_equalTo(25);
    }];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[POSListCell class] forCellReuseIdentifier:@"MyPOSListCellID"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.tableView.mj_header endRefreshing];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.Page += 1;
        if (self.Page <= self.MaxPage) {
            [self getPOSlist];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.secView.mas_bottom);
        make.bottom.equalTo(self.ChooseButton.mas_top);
    }];
    self.isZ = YES;
    self.numberback = [[UIButton alloc]init];
    [self.numberback addTarget:self action:@selector(numberbackClik) forControlEvents:UIControlEventTouchUpInside];
    self.numberback.backgroundColor = [UIColor clearColor];
    self.numberback.hidden = YES;
    [self.view insertSubview:self.numberback aboveSubview:self.tableView];
    [self.numberback mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.tableView);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNotification) name:@"FriendBack" object:nil];
}
- (void)loadNotification{
    if (self.dataArr.count > 0) {
        [self.dataArr removeAllObjects];
    }
    self.Page = 1;
    [self getPOSlist];
    [self performSelector:@selector(numberbackClik) withObject:nil afterDelay:0.3f];
}
- (void)numberbackClik{
    self.numberback.hidden = YES;
    [self.foot.numberfield becomeFirstResponder];
    [self.foot.numberfield resignFirstResponder];
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == self.foot.numberfield) {
        if ([textField.text containsString:@"."]) {
            textField.text = [textField.text substringToIndex:[textField.text rangeOfString:@"."].location];
        }
    }
}
- (void)getPOSlist{
    NSMutableDictionary *prams = [[NSMutableDictionary alloc]initWithDictionary:@{@"customerId":[UserDefaultsManager sharedInstance].user_id,@"current":[NSString stringWithFormat:@"%ld",self.Page],@"size":@"100"}];
    if (!self.timesort && !self.moneysort) {
        
    }else{
        if (self.timesort.length > 0) {
            if (self.isTimesort) {
                [prams setObject:self.timesort forKey:@"descs"];
                [prams setObject:@"" forKey:@"ascs"];
            }else{
                [prams setObject:self.timesort forKey:@"ascs"];
                [prams setObject:@"" forKey:@"descs"];
            }
        }
        if (self.moneysort.length > 0) {
            if (self.isMonetsort) {
                [prams setObject:self.moneysort forKey:@"descs"];
                [prams setObject:@"" forKey:@"ascs"];
            }else{
                [prams setObject:self.moneysort forKey:@"ascs"];
                [prams setObject:@"" forKey:@"descs"];
            }
        }
    }
    [[[POSStore alloc]init] GetUnActivePosWithPrams:prams Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.MaxPage = [res[@"data"][@"pages"] integerValue];
            self.foot.allnumber = [res[@"data"][@"total"] integerValue];
            NSArray *arr = res[@"data"][@"records"];
            if (arr.count > 0) {
                NSInteger maxnumber = [arr[0][@"backAmount"] integerValue];
                for (NSDictionary *dic in arr) {
                    if ([dic[@"backAmount"] integerValue] > maxnumber) {
                        maxnumber = [dic[@"backAmount"] integerValue];
                    }
                    PostlistModel *model = [PostlistModel mj_objectWithKeyValues:dic];
                    [self.dataArr addObject:model];
                }
                self.foot.cliknumber = 0;
                self.foot.minnumber = maxnumber;
            }else{
                [self showMBPError:@"暂无数据"];
            }
        }else{
            [self showMBPError:res[@"msg"]];
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } Failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)loadChoose{
    NSMutableArray *subArr = [[NSMutableArray alloc]init];
    if (self.mutArr.count > 0) {
        for (PostlistModel *model in self.mutArr) {
            [subArr addObject:model.sn];
        }
    }
    NSMutableDictionary *prams = [[NSMutableDictionary alloc]init];
    [prams setObject:[UserDefaultsManager sharedInstance].user_id forKey:@"fromId"];
    [prams setObject:self.foot.numberfield.text forKey:@"backAmount"];
    [prams setObject:subArr forKey:@"snList"];
    if (self.pushView.choosename.length > 0) {
        [prams setObject:self.pushView.choosename forKey:@"toName"];
        if (self.pushView.choosephone.length > 0) {
            [prams setObject:self.pushView.choosephone forKey:@"toPhone"];
            [self loadChooseData:prams];
        }else{
            [self showMBPError:@"请输入用户手机号"];
        }
    }else{
        [self showMBPError:@"请输入用户名"];
    }
}
- (void)loadChooseData:(NSDictionary *)prams{
    [[[POSStore alloc]init] PostPOSWithPrams:prams Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            [self CleanSuccessAlert:1];
            [self.pushView removeFromSuperview];
        }else{
            [self CleanSuccessAlert:0];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)CleanSuccessAlert:(NSInteger )type{
    [self.foot.numberfield becomeFirstResponder];
    [self.foot.numberfield resignFirstResponder];
    WS(weakself);
    self.success = [[PushView alloc]initWithChooseAlertType:type];
    [self.success setAlertTypeBlock:^{
        if (type == 0) {
            [weakself.success removeFromSuperview];
            weakself.pushView.hidden = NO;
        }
        if (type == 1) {
            if (weakself.dataArr.count > 0) {
                [weakself.dataArr removeAllObjects];
            }
            weakself.Page = 1;
            [weakself getPOSlist];
            [weakself.success removeFromSuperview];
            [weakself.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
        weakself.Fristindex = 0;
        weakself.Secondindex = 0;
    }];
    [self.view addSubview:self.success];
}
- (void)ChooseTypeClik{
    self.isZ = !self.isZ;
    for (UIView *sub in self.pushView.subviews) {
        if (sub.subviews.count > 0) {
            for (UIView *subb in sub.subviews) {
                if ([subb isKindOfClass:[UITextField class]]) {
                    UITextField *tet = (UITextField *)subb;
                    tet.text = @"";
                    [tet resignFirstResponder];
                }
            }
        }
    }
    [self.foot.numberfield resignFirstResponder];
}
- (void)tofriendView{
    [self numberbackClik];
    WS(weakself);
    if (self.isZ) {
        if (self.foot.numberfield.text.length > 0) {
            if ([NSString isNumber:self.foot.numberfield.text]) {
                NSInteger min = [self.foot.numberfield.text integerValue];
                if (min < 0) {
                    [self showMBPError:@"返现金额不能小于0"];
                }else if (min > self.foot.minnumber){
                    [self showMBPError:@"返现金额不能高于上限"];
                }else {
                    MyPOSlnactiveDirVC *VC = [[MyPOSlnactiveDirVC alloc]init];
                    VC.infoArr = _mutArr;
                    VC.minmoney = self.foot.numberfield.text;
                    [[AppDelegate sharedAppDelegate] pushViewController:VC];
                }
            }else{
                [self showMBPError:@"请输入数字"];
            }
        }else{
            [self showMBPError:@"请输入返现金额"];
        }
    }
    if (!self.isZ) {
        if (self.foot.numberfield.text.length > 0) {
            if ([NSString isNumber:self.foot.numberfield.text]) {
                NSInteger min = [self.foot.numberfield.text integerValue];
                if (min < 0) {
                    [self showMBPError:@"返现金额不能小于0"];
                }else if (min > self.foot.minnumber){
                    [self showMBPError:@"返现金额不能高于上限"];
                }else{
                    if ([self.view.subviews containsObject:self.pushView]) {
                        self.pushView.hidden = NO;
                    }else{
                        self.pushView.hidden = NO;
                        for (UIView *sub in self.pushView.subviews) {
                            if (sub.subviews.count > 0) {
                                for (UIView *subb in sub.subviews) {
                                    if ([subb isKindOfClass:[UITextField class]]) {
                                        UITextField *tet = (UITextField *)subb;
                                        tet.text = @"";
                                    }
                                }
                            }
                        }
                        [self.view addSubview:self.pushView];
                    }
                    [self.pushView setAlertsureBlock:^{
                        weakself.pushView.hidden = !weakself.pushView.hidden;
                        [weakself loadChoose];
                    }];
                }
            }else{
                [self showMBPError:@"请输入数字"];
            }
        }else{
            [self showMBPError:@"请输入返现金额"];
        }
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    POSListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyPOSListCellID"];
    if (self.dataArr.count > 0) {
        cell.typeV = self.VCType;
        cell.title.text = [NSString stringWithFormat:@"%ld",indexPath.section + 1];
        cell.indexarr = self.secView.subviews;
        cell.model = self.dataArr[indexPath.section];
    }
    [cell setCellFindBlock:^{
        PostlistModel *model = self.dataArr[indexPath.section];
        OrderCenterList *cen = [OrderCenterList sharedInstance];
        cen.selectedModel = [[OrderCenterModel alloc]init];
        cen.selectedModel.uid = model.orderId;
        if (self.delegate && [self.delegate respondsToSelector:@selector(CellPushNewinfo)]) {
            [self.delegate CellPushNewinfo];
        }
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.foot.numberfield resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isPiliang) {
        if (self.Fristindex > 0) {
            self.Secondindex = indexPath.section + 1;
        }else{
            self.Fristindex = indexPath.section + 1;
        }
        if (self.Fristindex == self.Secondindex) {
            [self willClik:indexPath];
        }else if(self.Fristindex != self.Secondindex && self.Secondindex != 0){
            if (self.Fristindex > self.Secondindex) {
                for (NSInteger i = self.Fristindex - 2; i >= self.Secondindex - 1; i--) {
                    PostlistModel *model = self.dataArr[i];
                    model.isClik = !model.isClik;
                }
            }else{
                for (NSInteger i = self.Fristindex; i <= self.Secondindex - 1; i++) {
                    PostlistModel *model = self.dataArr[i];
                    model.isClik = !model.isClik;
                }
            }
            [self.tableView reloadData];
            self.Secondindex = 0;
            self.Fristindex = 0;
            [self SelectWithNumber];
        }else{
            [self willClik:indexPath];
        }
    }else{
        self.Secondindex = 0;
        self.Fristindex = 0;
        [self willClik:indexPath];
    }
}
- (void)willClik:(NSIndexPath *)indexPath{
    PostlistModel *model = self.dataArr[indexPath.section];
    model.isClik = !model.isClik;
    POSListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.model = model;
    [self SelectWithNumber];
}
- (void)SelectWithNumber{
    NSInteger indexValue = 0;
    self.mutArr = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < self.dataArr.count; i++) {
        PostlistModel *model = self.dataArr[i];
        if (model.isClik) {
            [_mutArr addObject:model];
            indexValue += 1;
        }
    }
    if (_mutArr.count > 0) {
        PostlistModel *model = _mutArr[0];
        NSInteger minn = [model.backAmount integerValue];
        for (PostlistModel *model in _mutArr) {
            if (minn > [model.backAmount integerValue]) {
                minn = [model.backAmount integerValue];
            }
        }
        self.foot.minnumber = minn;
    }
    self.foot.cliknumber = indexValue;
    if (indexValue >= self.minPosFlow) {
        self.foot.tonext.enabled = YES;
    }else{
        self.foot.tonext.enabled = NO;
    }
}



@end
